package com.gupao.pattern.delegatestrategy.demo.delegate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class DispatcherServlet extends HttpServlet {

    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req,resp);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException {
        Handler handler = null;
        for (Handler h: handlerMapping){
            if (req.getRequestURL().toString().equals(h.getUrl())){
                handler = h;
                break;
            }
        }

        handler.method.invoke(handler.getController(),req.getParameter("productId"),req.getParameter("cost"),req.getParameter("number"));

    }

    @Override
    public void init() throws ServletException {
        Class<?> clazz = OrderController.class;
        try {
            handlerMapping.add(new Handler().setController(clazz.newInstance()).setMethod(clazz.getMethod("createOrder",new Class[]{String.class,double.class,int.class})).setUrl("/order/createOrder.do"));
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    class Handler {

        Object controller;
        Method method;
        String url;

        public Object getController() {
            return controller;
        }

        public Handler setController(Object controller) {
            this.controller = controller;
            return this;
        }

        public Method getMethod() {
            return method;
        }

        public Handler setMethod(Method method) {
            this.method = method;
            return this;
        }

        public String getUrl() {
            return url;
        }

        public Handler setUrl(String url) {
            this.url = url;
            return this;
        }
    }
}
